import React, { useState } from 'react';
import { Package, Download, Clock, Shield, FileCheck, Plus } from 'lucide-react';

interface DataPackage {
  id: string;
  generateTime: string;
  dataTypes: string[];
  fileSize: string;
  status: 'success' | 'processing' | 'failed';
  downloadCount: number;
  signature: string;
}

export const DataPackageGeneration: React.FC = () => {
  const [selectedTypes, setSelectedTypes] = useState<string[]>([]);
  const [isGenerating, setIsGenerating] = useState(false);
  
  // Mock data
  const [packages, setPackages] = useState<DataPackage[]>([
    {
      id: 'DP001',
      generateTime: '2024-12-01 15:30:00',
      dataTypes: ['公钥', '特殊访客名单', '院区设置'],
      fileSize: '2.5MB',
      status: 'success',
      downloadCount: 3,
      signature: 'SHA256:a1b2c3d4e5f6...'
    },
    {
      id: 'DP002',
      generateTime: '2024-11-30 10:15:00',
      dataTypes: ['被访人电话清单', '院区设置'],
      fileSize: '1.8MB',
      status: 'success',
      downloadCount: 5,
      signature: 'SHA256:f6e5d4c3b2a1...'
    },
    {
      id: 'DP003',
      generateTime: '2024-11-29 16:45:00',
      dataTypes: ['公钥', '特殊访客名单'],
      fileSize: '1.2MB',
      status: 'failed',
      downloadCount: 0,
      signature: ''
    }
  ]);

  const availableDataTypes = [
    '公钥',
    '特殊访客名单',
    '院区设置',
    '被访人电话清单',
    '系统配置参数'
  ];

  const handleTypeToggle = (type: string) => {
    setSelectedTypes(prev => 
      prev.includes(type) 
        ? prev.filter(t => t !== type)
        : [...prev, type]
    );
  };

  const handleGenerate = async () => {
    if (selectedTypes.length === 0) {
      alert('请至少选择一种数据类型');
      return;
    }

    setIsGenerating(true);
    
    // Simulate generation process
    setTimeout(() => {
      const newPackage: DataPackage = {
        id: `DP${(packages.length + 1).toString().padStart(3, '0')}`,
        generateTime: new Date().toLocaleString(),
        dataTypes: [...selectedTypes],
        fileSize: `${(Math.random() * 3 + 1).toFixed(1)}MB`,
        status: 'success',
        downloadCount: 0,
        signature: `SHA256:${Math.random().toString(36).substring(2, 16)}...`
      };
      
      setPackages([newPackage, ...packages]);
      setSelectedTypes([]);
      setIsGenerating(false);
      alert('数据包生成成功！');
    }, 3000);
  };

  const handleDownload = (pkg: DataPackage) => {
    // Simulate download
    console.log('Downloading package:', pkg.id);
    setPackages(packages.map(p => 
      p.id === pkg.id 
        ? { ...p, downloadCount: p.downloadCount + 1 }
        : p
    ));
    alert(`正在下载数据包 ${pkg.id}...`);
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'success':
        return 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200';
      case 'processing':
        return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200';
      case 'failed':
        return 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200';
      default:
        return 'bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-200';
    }
  };

  const getStatusText = (status: string) => {
    switch (status) {
      case 'success': return '生成成功';
      case 'processing': return '生成中';
      case 'failed': return '生成失败';
      default: return '未知状态';
    }
  };

  return (
    <div className="max-w-6xl mx-auto space-y-6">
      {/* Generation form */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6">
        <div className="flex items-center justify-between mb-6">
          <div>
            <h2 className="text-lg font-semibold text-gray-900 dark:text-white">数据包生成</h2>
            <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
              生成加密的数据同步包，用于内网系统间的数据传输
            </p>
          </div>
        </div>

        <div className="space-y-4">
          <div>
            <h3 className="text-md font-medium text-gray-900 dark:text-white mb-3">
              选择要包含的数据类型
            </h3>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
              {availableDataTypes.map((type) => (
                <label
                  key={type}
                  className={`flex items-center p-3 border rounded-lg cursor-pointer transition-colors ${
                    selectedTypes.includes(type)
                      ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
                      : 'border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-700'
                  }`}
                >
                  <input
                    type="checkbox"
                    checked={selectedTypes.includes(type)}
                    onChange={() => handleTypeToggle(type)}
                    className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                  />
                  <span className="ml-3 text-sm text-gray-900 dark:text-white">
                    {type}
                  </span>
                </label>
              ))}
            </div>
          </div>

          <div className="flex justify-end pt-4">
            <button
              onClick={handleGenerate}
              disabled={isGenerating || selectedTypes.length === 0}
              className="flex items-center px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              {isGenerating ? (
                <>
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                  生成中...
                </>
              ) : (
                <>
                  <Plus className="h-4 w-4 mr-2" />
                  生成数据包
                </>
              )}
            </button>
          </div>
        </div>
      </div>

      {/* Package history */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm">
        <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
          <h3 className="text-lg font-semibold text-gray-900 dark:text-white">历史生成记录</h3>
          <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
            查看已生成的数据包记录和下载状态
          </p>
        </div>

        <div className="p-6">
          {packages.length === 0 ? (
            <div className="text-center py-12">
              <Package className="mx-auto h-12 w-12 text-gray-400 mb-4" />
              <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
                暂无数据包记录
              </h3>
              <p className="text-gray-600 dark:text-gray-400">
                生成第一个数据包以查看记录
              </p>
            </div>
          ) : (
            <div className="space-y-4">
              {packages.map((pkg) => (
                <div key={pkg.id} className="border border-gray-200 dark:border-gray-700 rounded-lg p-4 hover:shadow-md transition-shadow">
                  <div className="flex items-start justify-between">
                    <div className="flex-1">
                      <div className="flex items-center gap-3 mb-2">
                        <span className="font-medium text-gray-900 dark:text-white">
                          {pkg.id}
                        </span>
                        <span className={`px-2 py-1 text-xs rounded-full ${getStatusColor(pkg.status)}`}>
                          {getStatusText(pkg.status)}
                        </span>
                        <span className="text-sm text-gray-500 dark:text-gray-500">
                          {pkg.fileSize}
                        </span>
                      </div>
                      
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                          <div className="flex items-center text-sm text-gray-600 dark:text-gray-400 mb-1">
                            <Clock className="h-3 w-3 mr-1" />
                            生成时间：{pkg.generateTime}
                          </div>
                          <div className="text-sm text-gray-600 dark:text-gray-400">
                            下载次数：{pkg.downloadCount} 次
                          </div>
                        </div>
                        
                        <div>
                          <p className="text-sm text-gray-600 dark:text-gray-400 mb-1">
                            包含数据：
                          </p>
                          <div className="flex flex-wrap gap-1">
                            {pkg.dataTypes.map((type) => (
                              <span
                                key={type}
                                className="px-2 py-1 text-xs bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200 rounded"
                              >
                                {type}
                              </span>
                            ))}
                          </div>
                        </div>
                      </div>

                      {pkg.signature && (
                        <div className="mt-2 p-2 bg-gray-50 dark:bg-gray-700 rounded text-xs">
                          <div className="flex items-center text-gray-600 dark:text-gray-400">
                            <Shield className="h-3 w-3 mr-1" />
                            数字签名：{pkg.signature}
                          </div>
                        </div>
                      )}
                    </div>

                    <div className="ml-4">
                      {pkg.status === 'success' && (
                        <button
                          onClick={() => handleDownload(pkg)}
                          className="flex items-center px-3 py-1 bg-green-600 text-white rounded hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 transition-colors"
                        >
                          <Download className="h-3 w-3 mr-1" />
                          下载
                        </button>
                      )}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Information panel */}
      <div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
        <h4 className="font-medium text-blue-900 dark:text-blue-200 mb-2">数据包说明</h4>
        <ul className="text-sm text-blue-800 dark:text-blue-300 space-y-1">
          <li>• 数据包采用AES-256加密，确保传输安全性</li>
          <li>• 每个数据包包含数字签名，用于验证完整性</li>
          <li>• 数据包格式为ZIP，可通过专用工具解析</li>
          <li>• 建议定期生成数据包，保持系统间数据同步</li>
        </ul>
      </div>
    </div>
  );
};